"""
视图模块
处理所有与url相关的操作
auth:@rqy,2021.6.1
"""

from OnlineShop.forms import *
from OnlineShop.models import *
from django.shortcuts import render

from test_dt import *


def hello(request):                 # 首页视图
    context = {"form": SearchForm(),
               "how_word": HotWord.objects.all(),
               "hot_recommend": GoodRecommend.objects.all(),
               "hot_sale": HotSale.objects.all()}
    return render(request, 'index.html', context)


def good_view(request, good_id):    # 商品视图
    context = {}
    try:                            # 尝试获得商品
        good_info = Good.objects.get(id=good_id)
        orders = Order.objects.filter(good=good_info)
    except:                 # 未找到，提示错误
        return render(request, 'base.html', {"message": f"您的商品{good_id}未找到，试着返回<a href='/'>主页</a>吧"})
    else:                           # 响应
        context["good_info"] = {"good": good_info}
        context["orders"] = orders
    return render(request, 'good.html', context)


def good_list(request):             # 商品列表视图
    context = {"good_list": Good.objects.all()}
    return render(request, 'good_list.html', context)


def sign_up(request):               # 注册视图
    content = {"post_url": "/sign_up/", "table_head": "账户注册", "post_name": "提交"}

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():         # 判断表单是否有效
            username = form.cleaned_data.get('username', '')
            email = form.cleaned_data.get('email', '')
            password = form.cleaned_data.get('password', '')
            address = form.cleaned_data.get('address', '')
            sex = form.cleaned_data.get('sex', 'F')
            sex_choose = {'M': 0, "F": 1}
            user = User.objects.filter(username=username)
            if not user:            # 判断对象是否存在，存在则不可重复创建
                user = User.objects.create_user(username=username, email=email, password=password)
                up = UserProfile(user=user, address=address, sex=sex_choose.get(sex, 'F'))
                up.save()
                return render(request, 'base.html', {"message": f"账号注册成功，试下<a href='/sign_in/'>登录</a>吧"})
            else:                   # 尝试恢复数据
                form = CreateUserForm()
                form.fields["username"].initial = username
                form.fields["email"].initial = email
                form.fields["password"].initial = password
                form.fields["address"].initial = address
                form.fields["sex"].initial = sex
                content['form'] = form
                content['errors'] = '用户名已存在'
    else:
        form = CreateUserForm()
        content['form'] = form
    return render(request, 'InputData.html', content)


def change_info(request):           # 信息修改
    content = {"post_url": "/change_info/", "table_head": "信息修改", "post_name": "提交"}
    if request.user.is_authenticated:                # 判断登录
        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():     # 表单非空
                username = form.cleaned_data.get('username', '')
                email = form.cleaned_data.get('email', '')
                password = form.cleaned_data.get('password', '')
                address = form.cleaned_data.get('address', '')
                sex = form.cleaned_data.get('sex', 'F')
                sex_choose = {'M': 0, "F": 1}
                user = User.objects.get(username=request.user)
                if user:            # 判断对象是否存在
                    if request.user.username != username:
                        if User.objects.filter(username=username):
                            form = CreateUserForm()
                            form.fields["username"].initial = username
                            form.fields["email"].initial = email
                            form.fields["password"].initial = password
                            form.fields["address"].initial = address
                            form.fields["sex"].initial = sex
                            content['form'] = form
                            content['errors'] = '用户名已存在'
                            return render(request, 'InputData.html', content)
                    user.username = username
                    user.email = email
                    user.set_password(password)
                    user.save()
                    up = UserProfile.objects.get(user=user)
                    up.sex = sex_choose[sex]
                    up.address = address
                    up.save()
                    return render(request, 'base.html', {"message": f"修改成功，重新<a href='/sign_in/'>登录</a>吧"})
        else:                           # 恢复初始化信息
            form = CreateUserForm()
            form.fields["username"].initial = request.user.username
            form.fields["email"].initial = request.user.email
            content['form'] = form
            content['form'] = form
        return render(request, 'InputData.html', content)
    else:
        return render(request, 'base.html', {"message": f"尚未登录，返回<a href='/'>主页"})


def user_center(request):               # 用户视图
    content = {}
    if request.user.is_authenticated:   # 确认登录
        user = User.objects.get(username=request.user)
        profile = UserProfile.objects.filter(user=user)
        if profile:                     # 用户信息
            profile = UserProfile.objects.get(user=user)
            sex_choose = {0: '男', 1: '女'}
            content['sex'] = sex_choose[profile.sex]
            content['address'] = profile.address
        orders = Order.objects.filter(user=user)
        if orders:                      # 订单列表
            content['orders'] = orders
    return render(request, 'user_center.html', content)


def buy_view(request, good_id):     # 购买视图
    if request.user.is_authenticated:
        try:
            user = User.objects.get(username=request.user.username)
            good = Good.objects.get(id=good_id)
        except:
            return render(request, 'base.html', {"message": f"商品未找到，返回<a href='/good_list/'>商品列表</a>"})
        else:
            if good.store:          # 检查库存
                good.store -= 1
                order = Order(user=user, good=good)
                good.save()
                order.save()
                return render(request, 'base.html', {"message": f"购买成功，快来<a href='/comment/{order.id}/'>评价</a>吧"})
            else:
                return render(request, 'base.html', {"message": f"商品数量不足，返回<a href='/good_list/'>商品列表</a>"})
    else:
        return render(request, 'base.html', {"message": f"尚未登录，请先<a href='/sign_in/'>登录</a>"})


def comment_view(request, order_id):    # 评论视图
    if request.user.is_authenticated:
        content = {"post_url": f"/comment/{order_id}/", "table_head": "评论", "post_name": "提交"}
        try:
            order = Order.objects.get(id=order_id)
        except:
            return render(request, 'base.html', {"message": f"订单未找到，返回<a href='/'>主页</a>"})
        else:
            if request.method == 'POST':
                form = CommentForm(request.POST)
                if form.is_valid():     # 表单完整
                    comment = form.cleaned_data.get('context', '')
                    order.comment = comment
                    order.save()
                    return render(request, 'base.html', {"message": f"评论成功，返回<a href='/user_center/'>个人中心</a>"})
            form = CommentForm()        # 恢复数据
            form.fields["context"].initial = order.comment
            content['form'] = form
            return render(request, 'InputData.html', content)
    else:
        return render(request, 'base.html', {"message": f"尚未登录，请先<a href='/sign_in/'>登录</a>"})


def search_view(request):               # 搜索视图
    context = {}
    if request.method == 'GET':
        good_ls = []
        text = request.GET.get("search_name", "")
        context["page_info"] = f"搜索结果：{text}"
        goods = Good.objects.all()
        for good in goods:
            if good.classify:
                if text in good.classify.classify:
                    good_ls.append(good)
                    continue

            if text in good.name or text in good.types or text in good.intro:
                good_ls.append(good)
                continue
        context["good_list"] = good_ls
        return render(request, 'good_list.html', context)
    return render(request, 'base.html', {"message": f"错误的访问，返回<a href='/'>主页</a>"})


def delete_order_view(request, order_id):
    if request.user.is_authenticated:                # 订单删除视图
        try:
            order = Order.objects.get(id=order_id)
        except:
            return render(request, 'base.html', {"message": f"订单未找到，返回<a href='/user_center/'>个人中心</a>"})
        else:
            if order.user == request.user:
                order.delete()
                return render(request, 'base.html', {"message": f"订单删除完成，返回<a href='/user_center/'>个人中心</a>"})
            else:
                return render(request, 'base.html', {"message": f"非子订单，返回<a href='/user_center/'>个人中心</a></div>"})
    else:
        return render(request, 'base.html', {"message": f"尚未登录，请先<a href='/sign_in/'>登录</a>"})


def random_get(request):
    if request.user.is_authenticated:                # 订单删除视图
        if request.user.has_perm('OnlineShop.add_good'):
            good_info = RandomGood.random_good()
            good = Good(name=good_info[0], classify=good_info[1],price=good_info[2], store=good_info[3], types=good_info[4], intro=good_info[5])
            good.save()
            return render(request, 'base.html', {"message": f"随机商品<b>{good.name}</b>添加成功"})
        else:
            return render(request, 'base.html', {"message": f"没有管理员权限，返回<a href='/'>主页</a>"})
    else:
        return render(request, 'base.html', {"message": f"尚未登录，请先<a href='/sign_in/'>登录</a>"})

